"""
    Controller for preorders.
"""

from sqlobject import declarative
from turbogears import expose, redirect, identity
from mnemoply import model
from mnemoply.error_handling import handle_std_exceptions
from mnemoply.utils import LocalMenu, LocalMenuItem
from mnemoply.preorders import preorders
from mnemoply.controllers.containers import Container
from mnemoply.utils import ExceptionsBunch

class PreorderController(LocalMenu):
    __metaclass__ = declarative.DeclarativeMeta

    def __classinit__(cls, new_attrs):
        if hasattr(cls, 'tag'):
            preorders.registerController(getattr(cls, 'tag'), cls())

    def __init__(self):
        super(PreorderController, self).__init__()

        self.local_menu.extend((
            LocalMenuItem(caption=_('List'), href='../list'),
            LocalMenuItem(caption=_('Fix'), href='./fix'),
            LocalMenuItem(caption=_('Preview'), href='./preview'),
            LocalMenuItem(caption=_('Delete'), href='./delete'),
        ))

    @expose()
    def delete(self, preorder):
        preorder.destroy()
        raise redirect('../')

    @handle_std_exceptions()
    @expose()
    def fix(self, preorder):
        order = preorder.fix()
        preorder.destroy()

        raise redirect("/Order/%d/" % order.id)

    @expose()
    def update_comment(self, preorder, comment):
        preorder.obj.comment = comment
        raise redirect('./')

    @expose()
    def preview(self, preorder):
        raise redirect(
            '/Report/%s/generate' % preorder.tag,
            preorder_id=preorder.obj.id,
            order_id=0
        )

class ListDataPreorderController(PreorderController):
    list_class = None
    list_title = None

    @expose()
    def show(self, preorder):
        return dict(
            tg_template="genshi:mnemoply.templates.preorders.list_data",
            title=self.list_title,
            list_class=self.list_class,
            preorder=preorder,
            local_menu=self.local_menu,
        )

    @expose()
    def delete_item(self, preorder, item_id):
        data = self.list_class.get(int(item_id))
        assert preorder.obj == data.preorder

        data.destroySelf()

        raise redirect('./')

class PreorderEndEducationController(ListDataPreorderController):
    tag = "EndEducation"
    list_class = model.PreorderEndEducationData
    list_title = _("Students")

class PreorderGroupInclusionController(ListDataPreorderController):
    tag = "GroupInclusion"
    list_class = model.PreorderGroupIncData
    list_title = _("Students and according groups")

class PreorderGroupDischargeController(ListDataPreorderController):
    tag = "GroupDischarge"
    list_class = model.PreorderGroupDisData
    list_title = _("Students and according groups")

class PreorderGroupTransferController(ListDataPreorderController):
    tag = "GroupTransfer"
    list_class = model.PreorderGroupTransData
    list_title = _("Students and according groups")

def check_order_access(pTypeTag):
    if not identity.has_any_permission('dba', 'Order:%s' % pTypeTag):
        raise identity.IdentityFailure([]) ### FIXME?

class PreordersController(Container):
    def _get_item(self, name):
        try:
            obj = model.Preorder.get(int(name))
            check_order_access(obj.pTypeTag)

            preorder = preorders.obj2preorder(obj)
            controller = preorders.obj2controller(obj)
            return preorder, controller
        except:
            return None

    @expose()
    def index(self):
        raise redirect('list')

    @expose(template="genshi:mnemoply.templates.preorder_list")
    def list(self):
        preorder_list = [record for record in model.Preorder.select()]
        preorder_list.sort(key=lambda x: x.owner.user_name)
        preorder_list.sort(key=lambda x: x.creationDate)
        return dict(preorder_list=preorder_list)

    @expose()
    def add(self, tag):
        check_order_access(tag)

        preorder = preorders.create(tag)

        raise redirect("%d/" % preorder.obj.id)

exposed = PreordersController()
